﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Fitness_club
{
    public partial class RemainderForm : Form
    {
        public static string constr = ConfigurationManager.AppSettings["ConStr"];
        
        private String smsUserName=null;
        private String smsPassword = null;
        private String remainderMessage = null;
        private String birthdayWishMessage = null;
        private String dueMemberContactNo;
        List<string> dueMemberList = new List<string>();
        List<string> bdayMemberList = new List<string>();
       
        public RemainderForm()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void fetchFeesDueMembers()
        {
            try
            {
                DateTime today = DateTime.Today;
                String todayDate = today.ToString(Constants.DATE_FORMAT);
                SqlDataAdapter adapter = new SqlDataAdapter("select m.id as Id,m.firstname as [First Name],m.lastname as [Last Name],sp.type as [Plan Type],sp.amount as Amount,m.contactno as [Contact No],m.due_date as [Due Date] from member m LEFT JOIN subscription_plan sp ON m.mem_plan=sp.id where m.status='A' and due_date  < = GETDATE()+7 order by due_date", constr);
                DataTable dTable = new DataTable();
                DataSet dt = new DataSet();
                adapter.Fill(dt, "member");
                adapter.Fill(dTable);

                if (dt.Tables.Count > 0)
                {
                    buttonSms.Enabled = true;
                }
                else
                {
                    buttonSms.Enabled = false;
                    DialogResult result = MessageBox.Show("No Transactions found", "Transactions", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        this.BeginInvoke(new MethodInvoker(Close));
                    }

                }

                dataGridView1.DataSource = dTable;

                foreach (DataRow row in dt.Tables["member"].Rows)
                {
                    dueMemberList.Add(row["Contact No"].ToString());
                }
                //sendDueSms(authorNames);
            }
            catch (Exception exce)
            {
                MessageBox.Show("Fetch Fess Due Member Failed, Try Again", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }


        private void fetchBdayRemainderMembers()
        {
            try
            {
                DateTime today = DateTime.Today;
                String todayDate = today.ToString(Constants.DATE_FORMAT);
                SqlDataAdapter adapter = new SqlDataAdapter("select m.id as Id,m.firstname as [First Name],m.lastname as [Last Name],m.contactno as [Contact No] from member m  where m.status='A' and DAY(GETDATE()+1) = DAY(m.dob) AND MONTH(GETDATE()+1) = MONTH(m.dob)", constr);
                DataTable dTable = new DataTable();
                DataSet dt = new DataSet();
                adapter.Fill(dt, "m");
                adapter.Fill(dTable);

                if (dt.Tables.Count > 0)
                {
                    buttonBdayRemainder.Enabled = true;
                }
                else
                {
                    buttonBdayRemainder.Enabled = false;
                    //DialogResult result = MessageBox.Show("No Transactions found", "Transactions", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //if (result == DialogResult.OK)
                    //{
                    //    this.BeginInvoke(new MethodInvoker(Close));
                    //}
                }

                dataGridViewBirthdayMem.DataSource = dTable;

                foreach (DataRow row in dt.Tables["m"].Rows)
                {
                    bdayMemberList.Add(row["Contact No"].ToString());
                }
                //sendDueSms(authorNames);
            }
            catch (Exception exce)
            {
                MessageBox.Show("Fetch Birthday Remainder for Member Failed, Try Again", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void RemainderForm_Load(object sender, EventArgs e)
        {
           
            readSmsSettings();
            fetchFeesDueMembers();
            fetchBdayRemainderMembers();
        }

        private void buttonSms_Click(object sender, EventArgs e)
        {
           
        }

        private void readSmsSettings()
        {
            try
            {
                System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                smsUserName = config.AppSettings.Settings["SmsUserName"].Value;
                smsPassword = config.AppSettings.Settings["SmsPassword"].Value;
                remainderMessage = config.AppSettings.Settings["RemainderMessage"].Value;
                birthdayWishMessage = config.AppSettings.Settings["BirthdayWishMessage"].Value;
            }
            catch
            {
                MessageBox.Show("Failed to read sms settings", "Sms Settings", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

        private void buttonBdayRemainder_Click(object sender, EventArgs e)
        {
        }

        private void buttonSms_Click_1(object sender, EventArgs e)
        {
            
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void buttonSms_Click_2(object sender, EventArgs e)
        {
            try
            {
                String[] contactNos = dueMemberList.ToArray();
                String contactNo = String.Join(",", contactNos);
                string strUrl = "http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=" + smsUserName + ":" + smsPassword + "&senderID=TEST SMS&receipientno=" + contactNo + "&msgtxt=" + remainderMessage + "&state=4";
                WebRequest request = HttpWebRequest.Create(strUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream s = (Stream)response.GetResponseStream();
                StreamReader readStream = new StreamReader(s);
                String dataString = readStream.ReadToEnd();

                string regexPattern = @"(?<=Status=)[^,\n]*";
                var statusCode = Regex.Match(dataString, regexPattern).Value;

                string statusMessage = dataString.Substring(dataString.LastIndexOf(',') + 1);
                response.Close();
                s.Close();
                readStream.Close();
                if (statusCode == "0")
                {
                    MessageBox.Show("Remainder sent successfully", "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (statusCode == "1")
                {
                    MessageBox.Show("Remainder sending failed," + statusMessage, "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                this.Close();
            }
            catch
            {
                MessageBox.Show("Failed to send sms", "SMS", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }            
        }

        private void buttonBdayRemainder_Click_1(object sender, EventArgs e)
        {
            try
            {
                String[] contactNos = bdayMemberList.ToArray();
                String contactNo = String.Join(",", contactNos);
                string strUrl = "http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=" + smsUserName + ":" + smsPassword + "&senderID=TEST SMS&receipientno=" + contactNo + "&msgtxt=" + birthdayWishMessage + "&state=4";
                WebRequest request = HttpWebRequest.Create(strUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream s = (Stream)response.GetResponseStream();
                StreamReader readStream = new StreamReader(s);
                String dataString = readStream.ReadToEnd();

                string regexPattern = @"(?<=Status=)[^,\n]*";
                var statusCode = Regex.Match(dataString, regexPattern).Value;

                string statusMessage = dataString.Substring(dataString.LastIndexOf(',') + 1);
                response.Close();
                s.Close();
                readStream.Close();
                if (statusCode == "0")
                {
                    MessageBox.Show("Birthdat wishes sent successfully", "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (statusCode == "1")
                {
                    MessageBox.Show("Birthday wishes sending failed," + statusMessage, "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                this.Close();
            }
            catch
            {
                MessageBox.Show("Failed to Birthday Remainder", "Birthday Remainder", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        
        }

        
    }
}
